package com.tma.intern;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadFile
 */
public class DownloadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final int BUFSIZE = 100*1024;//100 KB
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String fileName = request.getParameter("name");
		ServletOutputStream op = response.getOutputStream();
		int page = 0;
		try {
			page = Integer.parseInt(request.getParameter("page"));
			
		} catch (Exception e){
			System.out.println(request.getParameter("page"));
			return;
		}
		File                f        = new File(getServletContext().getRealPath("/") +UploadFileServlet.PATH+"/"+fileName+"/"+page+".png");
        int                 length   = 0;
        
        ServletContext      context  = getServletConfig().getServletContext();
        String              mimetype = context.getMimeType( fileName );

        //  Set the response and go!
        //
        response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
        response.setContentLength( (int)f.length() );
        response.setHeader( "Content-Disposition", "attachment; filename=\"" + fileName + "\"" );

        //
        //  Stream to the requester.
        //
        
        byte[] bbuf = new byte[BUFSIZE];
        DataInputStream in = new DataInputStream(new FileInputStream(f));

        while ((in != null) && ((length = in.read(bbuf)) != -1))
        {
            op.write(bbuf,0,length);
        }
        in.close();
        op.flush();
        op.close();
	}

}
